/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.Produccion; 

import Controlador.Bean.Almacen.ProdxSolicitudMovimiento;
import Controlador.Bean.Almacen.SolicitudMovimiento;
import Controlador.Bean.Compras.ProductoxOrden;
import Controlador.Bean.Compras.Proveedor;
import Controlador.Bean.Compras.Solicitud;
import Controlador.Bean.Produccion.Maquina;
import Controlador.Bean.Produccion.DesempenoHistorico;
import Controlador.Bean.Produccion.ProduccionReal;


import Controlador.Bean.RRHH.Personal;
import Controlador.Bean.Simulacion.PlanProdTeorico;
import Controlador.Bean.Simulacion.ProduccionTeorica;
import Controlador.Bean.Simulacion.ProduccionxProducto;
import Controlador.Bean.Simulacion.Trabajador;
import Controlador.Bean.Ventas.PlanVentas;
import Controlador.Service.Almacen.GestionAlmacenes;
import Controlador.Service.Almacen.ServicioAlmacen;
import Controlador.Service.Compras.GestionCompra;
import Controlador.Service.Compras.ServicioProveedor;
import Controlador.Service.Produccion.GestionProduccion;
import Controlador.Service.Produccion.ServicioAsignacionReal;
import Controlador.Service.Simulacion.ServicioProduccionTeorica;
import Controlador.Service.Simulacion.ServicioSimulacion;
import Controlador.Service.Ventas.GestionVentas;
import Data.config.SessionFac;
import static gui.Compras.AgregarOrdenCompra.txtIdProveedor;
import gui.Compras.OCSeleccionarProveedor;
import gui.Compras.gestionCompras;
import gui.General.Main;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableRowSorter;
import org.apache.ibatis.session.SqlSession;

/**
 *
 * @author LAZO_PAZCE
 */
public class asignacionHM extends javax.swing.JInternalFrame {

 
private  boolean existe = false;
private   ArrayList<Maquina> maquinasHabilitadas = new ArrayList();
private ArrayList<PlanVentas> PlanDeVentas = new ArrayList();
private Date FechaPlanDeVentas;
TableModel tb;
TableModelPV tbPV;
TreeMap<Date, HashMap<String, HashMap<String, ArrayList<ProduccionxProducto>>>> simulacion;
List<String> turnos;
HashMap<String, DesempenoHistorico> asignacion;
HashMap<String, Trabajador> empleadosNoAsignados;
    public asignacionHM() {
        initComponents();
        HabilitarMaquinas();
        txtTotalEmp.setEditable(false);
        txtHorneado.setEditable(false);
        txtDecorado.setEditable(false);
        txtRellenado.setEditable(false);
        txtEmpaquetado.setEditable(false);
        initComp();
        ActualizarMaquinas();
         Vector vector = new Vector();
         vector.add(null);
         vector.add("Enero");
         vector.add("Febrero");
         vector.add("Marzo");
         vector.add("Abril");
         vector.add("Mayo");
         vector.add("Junio");
         vector.add("Julio");
         vector.add("Agosto");
         vector.add("Septiembre");
         vector.add("Octubre");
         vector.add("Noviembre");
         vector.add("Diciembre");

         DefaultComboBoxModel comboModelo = new DefaultComboBoxModel(vector);
         cmbFechasPlan.setModel(comboModelo);
         GestionVentas gestorVentas = Controlador.Service.Ventas.GestionVentas.getInstance();
        PlanDeVentas = gestorVentas.queryAllPlanes();
        tb= new TableModel();
        tbPV= new TableModelPV();
        tablaPlan.setModel(tb); 
        tablaPlanV.setModel(tbPV);
        TableRowSorter<TableModel> sorter  = new TableRowSorter<TableModel>((TableModel) tablaPlan.getModel());
        tablaPlan.setRowSorter(sorter);
        
        //dpFechaData.setEnabled(false);
    }
    
    class TableModel extends AbstractTableModel{
        
        //Two arrays used for the table data
        String[] columnNames = {"Turno","Trabajador", "Tipo de Maquina","Produccion","Perdida"};
        Map<String,HashMap<String,Object>> turnos;
        Map<String,HashMap<String,Object>> empleados;
        TreeMap<String,String> tipoMaquina;
        
               
        public List<DesempenoHistorico> data = new ArrayList<DesempenoHistorico>();
        
        
        public void actualizarTabla(List<DesempenoHistorico> data){
            this.data = data;
            fireTableDataChanged();
        }
        
        public void actualizarTabla(Map<String,HashMap<String,Object>> turnos,TreeMap<String,String>tipoMaquina,Map<String,HashMap<String,Object>> empleados){
            this.turnos=turnos;
            this.tipoMaquina=tipoMaquina;
            this.empleados=empleados;
        }

        @Override
        public int getRowCount()
        {
            return data.size();
        }                
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {               
            switch(column){
                case 0: return turnos.get(data.get(row).getIdTurno()).get("nombre");
                case 1: return empleados.get(data.get(row).getIdEmpleadoOp()).get("nombre");                       
                case 2: return tipoMaquina.get(data.get(row).getIdMaquina());
                case 3: return data.get(row).getProduccion();
                case 4: return data.get(row).getPerdida();
                default: return "";
                    
                    
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
            if(c!=2){
            return getValueAt(0, c).getClass();
            }else{
                return JButton.class;
            }
        }
        
        @Override
        public boolean isCellEditable(int row, int column)
        {
	        return false;
        }
        
     } 
    
    
    class TableModelPV extends AbstractTableModel{
        
        //Two arrays used for the table data
        String[] columnNames = {"Nombre de producto","Cantidad requerida", "Cantidad teoricamente producida"};
        List<HashMap<String,Object>> PVO;
        List<HashMap<String,Object>> PVA;
        Map<String,HashMap<String,Object>> nombresProds;
        HashMap<String, Trabajador> empleadosNoAsignados;       
       
        
        
        public void actualizarTabla(List<HashMap<String,Object>> PVA){
            this.PVA = PVA;
            fireTableDataChanged();
        }
        
          public void actualizarTabla(List<HashMap<String,Object>> PVO,Map<String,HashMap<String,Object>> nombresProds){
            this.PVO = PVO;
            this.nombresProds=nombresProds;
            this.PVA =null;
            fireTableDataChanged();
        }
        
       

        public int getRowCount()
        {
            return PVO==null?0:PVO.size();
        }
        
        
        @Override
        public int getColumnCount()            
        {
            return columnNames.length;
        }
        
        @Override
        public Object getValueAt(int row, int column)
        {   
            switch(column){
                case 0: return nombresProds.get(PVO.get(row).get("idproducto")).get("nombre");
                case 1: return PVO.get(row).get("cantidadfinal");                       
                case 2: return PVA!=null?((Long)PVO.get(row).get("cantidadfinal")-(Long)PVA.get(row).get("cantidadfinal")):"-";                
                default: return "";  
            }
        }
        
        //Used by the JTable object to set the column names
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        //Used by the JTable object to render different
        //functionality based on the data type
        @Override
        public Class getColumnClass(int c) {
          
            return getValueAt(0, c).getClass();
        }
        
        @Override
        public boolean isCellEditable(int row, int column)
        {
	        return false;
        }
        
     } 

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jTextField4 = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jTextField5 = new javax.swing.JTextField();
        jTextField6 = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtTotalEmp = new javax.swing.JTextField();
        txtDecorado = new javax.swing.JTextField();
        txtHorneado = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtEmpaquetado = new javax.swing.JTextField();
        txtRellenado = new javax.swing.JTextField();
        btnSeleccionarMaquinas = new javax.swing.JButton();
        btnGenerarAsignacion = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tablaPlan = new javax.swing.JTable();
        btnGuardar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnSeleccionarTrabajadores2 = new javax.swing.JButton();
        cmbFechasPlan = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        tablaPlanV = new javax.swing.JTable();
        btnOpNAsg = new javax.swing.JButton();

        setClosable(true);
        setTitle("Asignación Hombre - Máquina");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cantidad a Producir"));

        jLabel4.setText("Galleta A");

        jLabel5.setText("Galleta B");

        jLabel6.setText("Galleta C");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Resumen de Cantidades"));

        jLabel1.setText("Maquinas de Decorado");

        jLabel2.setText("Maquinas de Horneado");

        jLabel3.setText("Total de Operarios");

        txtTotalEmp.setFocusCycleRoot(true);
        txtTotalEmp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtTotalEmpActionPerformed(evt);
            }
        });

        jLabel7.setText("Maquinas de Rellenado");

        jLabel8.setText("Maquinas de Empaquetado");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel7)
                    .addComponent(jLabel1)
                    .addComponent(jLabel8)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtDecorado, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                    .addComponent(txtTotalEmp, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                    .addComponent(txtHorneado, javax.swing.GroupLayout.DEFAULT_SIZE, 77, Short.MAX_VALUE)
                    .addComponent(txtRellenado)
                    .addComponent(txtEmpaquetado))
                .addContainerGap(33, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtTotalEmp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtHorneado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txtDecorado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtRellenado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7))
                .addGap(18, 18, 18)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtEmpaquetado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        btnSeleccionarMaquinas.setText("Seleccionar Maquinas");
        btnSeleccionarMaquinas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarMaquinasActionPerformed(evt);
            }
        });

        btnGenerarAsignacion.setText("Generar Asignación");
        btnGenerarAsignacion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenerarAsignacionActionPerformed(evt);
            }
        });

        jScrollPane2.setBorder(javax.swing.BorderFactory.createTitledBorder("Asignación Hombre-Maquina"));

        tablaPlan.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        tablaPlan.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tablaPlan);

        jScrollPane2.setViewportView(jScrollPane1);

        btnGuardar.setText("Guardar");
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Descartar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnSeleccionarTrabajadores2.setText("Seleccionar trabajadores");
        btnSeleccionarTrabajadores2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarTrabajadores2ActionPerformed(evt);
            }
        });

        cmbFechasPlan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmbFechasPlanActionPerformed(evt);
            }
        });

        jLabel9.setText("Mes del plan de ventas:");

        jScrollPane3.setBorder(javax.swing.BorderFactory.createTitledBorder("Plan de venta seleccionado"));

        tablaPlanV.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(tablaPlanV);

        btnOpNAsg.setText("Operadores no asignados");
        btnOpNAsg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpNAsgActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(22, 22, 22)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(cmbFechasPlan, 0, 161, Short.MAX_VALUE)
                            .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                            .addComponent(btnSeleccionarMaquinas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnGenerarAsignacion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnSeleccionarTrabajadores2, javax.swing.GroupLayout.DEFAULT_SIZE, 161, Short.MAX_VALUE)
                            .addComponent(btnOpNAsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(394, Short.MAX_VALUE)
                .addComponent(btnGuardar)
                .addGap(178, 178, 178)
                .addComponent(btnCancelar)
                .addGap(391, 391, 391))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(555, Short.MAX_VALUE)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 548, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cmbFechasPlan, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSeleccionarTrabajadores2)
                        .addGap(18, 18, 18)
                        .addComponent(btnSeleccionarMaquinas)
                        .addGap(18, 18, 18)
                        .addComponent(btnGenerarAsignacion)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpNAsg))
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnCancelar)
                    .addComponent(btnGuardar))
                .addContainerGap(19, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(258, Short.MAX_VALUE)))
        );

        jPanel2.getAccessibleContext().setAccessibleName("Resumen de cantidades");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionarTrabajadoresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

    }//GEN-LAST:event_jButton1ActionPerformed
   
    private void btnSeleccionarMaquinasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarMaquinasActionPerformed

       
         ArrayList<Maquina> maquinasSeleccionables = new ArrayList();
         HabilitarMaquinas();
        maquinasHabilitadas = (ArrayList)Controlador.Service.Produccion.GestionProduccion.obtenerMaquinasHabilitadas();
        maquinasSeleccionables = (ArrayList)Controlador.Service.Produccion.GestionProduccion.obtenerMaquinas();
         SeleccionarMaquinas SM = new SeleccionarMaquinas(maquinasHabilitadas, maquinasSeleccionables,this);
         Main.getDesktop().add(SM);
         SM.setVisible(true);
         
    }//GEN-LAST:event_btnSeleccionarMaquinasActionPerformed

    private void btnGenerarAsignacionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenerarAsignacionActionPerformed
        // TODO add your handling code here:
        if(existe){
        ServicioSimulacion serviceSimulacion = new ServicioSimulacion();
        HashMap<String,Object> resultados=serviceSimulacion.ejecutarAlgoritmo(FechaPlanDeVentas);
        if(resultados.get("error")!=null){
            JOptionPane.showMessageDialog(this, "Se han detectado los siguientes errores:\n"+((String)resultados.get("error")));
            return ;
        }
        tbPV.actualizarTabla((List<HashMap<String,Object>>)resultados.get("planVentasFaltante"));
        ArrayList<PlanProdTeorico> lista= new ArrayList<>();
        TreeMap<Date, HashMap<String, HashMap<String, ArrayList<ProduccionxProducto>>>> temp=(TreeMap<Date, HashMap<String, HashMap<String, ArrayList<ProduccionxProducto>>>>)resultados.get("planProd");
        turnos=(List<String>)resultados.get("turnos");
        simulacion=temp;
        asignacion=(HashMap<String, DesempenoHistorico>) resultados.get("asigHMHS");
        empleadosNoAsignados=(HashMap<String, Trabajador>) resultados.get("trabajadores");
        if(empleadosNoAsignados!=null && !empleadosNoAsignados.isEmpty()) btnOpNAsg.setVisible(true);
        SqlSession sqlsession = SessionFac.SessionFactory().openSession();
        tb.actualizarTabla(serviceSimulacion.obtenerTurnosC(sqlsession), serviceSimulacion.obtenerTipoMaquina(sqlsession),serviceSimulacion.obtenerDatosTrabajador(sqlsession));
        sqlsession.close();
        tb.actualizarTabla((List<DesempenoHistorico>)resultados.get("asigHM"));
        cmbFechasPlan.setEnabled(false);
        btnSeleccionarMaquinas.setEnabled(false);
        btnSeleccionarTrabajadores2.setEnabled(false);
        }else{
            JOptionPane.showMessageDialog(this, "Debe seleccionar un mes que tenga plan de ventas");
        }
    }//GEN-LAST:event_btnGenerarAsignacionActionPerformed

    private void btnSeleccionarTrabajadores2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarTrabajadores2ActionPerformed
         ArrayList<Personal> Empleados = new ArrayList();
         Empleados = (ArrayList<Personal>) Controlador.Service.RRHH.GestionRRHH.obtenerObrerosEstadoCorrida();
         SeleccionarTrabajadores ST = new SeleccionarTrabajadores(Empleados,this);
         Main.getDesktop().add(ST);
         ST.setVisible(true);
    }//GEN-LAST:event_btnSeleccionarTrabajadores2ActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        turnos=null;
        simulacion=null;
        cmbFechasPlan.setEnabled(true);
        btnSeleccionarMaquinas.setEnabled(true);
        btnSeleccionarTrabajadores2.setEnabled(true);
        btnOpNAsg.setVisible(false);
        try{
        tb.actualizarTabla(new ArrayList<DesempenoHistorico>());
        }
        catch(Exception e){
        }
                
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void txtTotalEmpActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtTotalEmpActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtTotalEmpActionPerformed

    private void cmbFechasPlanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbFechasPlanActionPerformed
        // TODO add your handling code here:

        int mes = cmbFechasPlan.getSelectedIndex() - 1;
      //dpFechaData.setEnabled(false); 
        existe=false;
        int indice =0;
        btnOpNAsg.setVisible(false);
        for(indice = 0; indice<PlanDeVentas.size(); indice++){          
            if(PlanDeVentas.get(indice).getFechaInicio().getMonth() == mes){
                existe = true;
                break;
            }
        }
        if(existe){
            
           this.FechaPlanDeVentas = PlanDeVentas.get(indice).getFechaInicio();
            SqlSession sqlsession= SessionFac.SessionFactory().openSession();
            try{
                ServicioSimulacion serv= new ServicioSimulacion();
                
                
                List<HashMap<String,Object>> PVO=serv.obtenerPlanDeVentas(FechaPlanDeVentas, sqlsession);
                Map<String,HashMap<String,Object>> nombresProds=serv.obtenerNombProds(sqlsession);
                if(PVO!=null && nombresProds!=null)
                    tbPV.actualizarTabla(PVO, nombresProds);
                else
                    tbPV.actualizarTabla(new ArrayList<HashMap<String,Object>>(), null);
            }
            finally{
            sqlsession.close();
            }
            
                        
        }else{
            tbPV.actualizarTabla(new ArrayList<HashMap<String,Object>>(), null);
            JOptionPane.showMessageDialog(this,"No existe un plan de ventas para el mes seleccionado");
        }
    }//GEN-LAST:event_cmbFechasPlanActionPerformed

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        Calendar calendarA= Calendar.getInstance();
        calendarA.setTime(FechaPlanDeVentas);
        calendarA.setTime(FechaPlanDeVentas);
        calendarA.add(Calendar.MONTH, 1);
        calendarA.set(Calendar.DAY_OF_MONTH, 1);
        Date fin=calendarA.getTime();
        calendarA.add(Calendar.MONTH, -1);
        ArrayList<ProduccionTeorica> lista= new ArrayList<>();
        for(calendarA.setTime(calendarA.getTime());!calendarA.getTime().equals(fin);calendarA.add(Calendar.DATE, 1)){
            for(int i=0;i<turnos.size();i++){
                Iterator<Map.Entry<String, ArrayList<ProduccionxProducto>>> it=simulacion.get(calendarA.getTime()).get(turnos.get(i)).entrySet().iterator();
                while(it.hasNext()){
                    Map.Entry<String, ArrayList<ProduccionxProducto>> mapa= it.next();
                    ArrayList<ProduccionxProducto> listaProds=mapa.getValue();
                    for(int j=0;j<listaProds.size();j++){
                        ProduccionTeorica plan= new ProduccionTeorica();
                        plan.setIdEmpleado(mapa.getKey());
                        plan.setIdProducto(listaProds.get(j).getCodProducto().split("\\.")[1]);
                        plan.setIdTurno(turnos.get(i));
                        plan.setCantidad(listaProds.get(j).getProduccion());
                        plan.setMerma(listaProds.get(j).getPerdida());
                        plan.setFecha(calendarA.getTime());
                        plan.setIdProduccionTeorica("");
                        plan.setIdMaquina(asignacion.get(mapa.getKey()).getIdMaquina());
                        lista.add(plan);
                    }
                }
            }
        }
        ServicioProduccionTeorica servProdTeorica= new ServicioProduccionTeorica();
        new  ServicioSimulacion().guardarSimulacion(new ArrayList<DesempenoHistorico>(this.asignacion.values()));
        servProdTeorica.insertar(lista);
//ORDEN DE COMPRA
        int resultado = JOptionPane.showConfirmDialog(this, "¿Desea generar órdenes de compra?");
        if(resultado==0){
            ServicioAsignacionReal ar = new ServicioAsignacionReal();
            List<ProduccionReal> data = ar.obtenerServicioAsignacionRealMes();
            ServicioProveedor sp = new ServicioProveedor();
            List<Proveedor> proveedor = sp.seleccionarTodo();
            String iorden;
            List<ProduccionReal> pr = ar.obtenerServicioAsignacionRealMes();
            
            for(int i=0; i<pr.size(); i++){
                iorden=Controlador.Service.Compras.GestionCompra.obtenerIdSiguienteOC();
                HashMap<String, Double> productos = obtenerEntradas(pr.get(i));
                List<String> codigos;
                codigos = new ArrayList<String>(productos.keySet());
                Double pfinal = 0.0;
                List<ProductoxOrden> prod = new ArrayList<>();
                for(int j=0; j<codigos.size(); j++){
                     double precio = GestionAlmacenes.obtenerPrecio(codigos.get(j));
                     ProductoxOrden p = new ProductoxOrden(iorden,codigos.get(j),j+1,precio,productos.get(codigos.get(j)).intValue(),productos.get(codigos.get(j))*precio);
                     prod.add(p);
                     //GestionCompra.agregarProductoxOrden(p,iorden);
                     pfinal+=productos.get(codigos.get(j))*precio;
                }
                
                 Solicitud s= new Solicitud(iorden,proveedor.get(0).getIdProveedor(),Main.usu.getIdEmpleadoAdm(),
                0,new Date(),pfinal,"0");

                GestionCompra.agregarSolicitud(s);
                
                for(int j=0; j<prod.size(); j++){
                    GestionCompra.agregarProductoxOrden(prod.get(j),iorden);
                }
            }
         JOptionPane.showMessageDialog(this, "Asignación Terminada");
         this.dispose();
        }
        
        
        
    }//GEN-LAST:event_btnGuardarActionPerformed

    public HashMap<String, Double> obtenerEntradas(ProduccionReal pr){
        HashMap<String, Double> hm = new HashMap<>();
        List<HashMap<String,Object>> productos = GestionProduccion.seleccionarProdFase(pr.getIdProducto());
        
        int cantidad = 0;
        Double aux = 0.0;
        for(int i=0; i<productos.size(); i++){
             if("S".compareTo((String)productos.get(i).get("entradasalida"))==0){
                 if(cantidad != 0){ 
                     aux = hm.get((String)productos.get(i).get("idproducto"));
                 }
                 hm.put((String)productos.get(i).get("idproducto"),(Double)productos.get(i).get("cantidad"));
                 cantidad++;
             }else{
                 if(cantidad==1){
                     hm.put((String)productos.get(i).get("idproducto"),(Double)productos.get(i).get("cantidad")*(pr.getCantidadFicticia()+pr.getMermaFicticia()));
                 }else{
                     hm.put((String)productos.get(i).get("idproducto"),(Double)productos.get(i).get("cantidad")*aux*(pr.getCantidadFicticia()+pr.getMermaFicticia()));
                 }
             }
        }
        List<String> producto = new ArrayList<String>(hm.keySet());
        for(int i=0;i<producto.size();i++){
            if(producto.get(i).contains("TER")||producto.get(i).contains("INT")){
                hm.remove(producto.get(i));
            }
        }
        
        return hm;
    }
    
    private void btnOpNAsgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpNAsgActionPerformed
        TrabajadoresNoSeleccionados vnt= new TrabajadoresNoSeleccionados(null, closable, new ArrayList<Trabajador>(empleadosNoAsignados.values()));
        vnt.setVisible(true);
    }//GEN-LAST:event_btnOpNAsgActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnGenerarAsignacion;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JButton btnOpNAsg;
    private javax.swing.JButton btnSeleccionarMaquinas;
    private javax.swing.JButton btnSeleccionarTrabajadores2;
    private javax.swing.JComboBox cmbFechasPlan;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextField jTextField4;
    private javax.swing.JTextField jTextField5;
    private javax.swing.JTextField jTextField6;
    private javax.swing.JTable tablaPlan;
    private javax.swing.JTable tablaPlanV;
    private javax.swing.JTextField txtDecorado;
    private javax.swing.JTextField txtEmpaquetado;
    private javax.swing.JTextField txtHorneado;
    private javax.swing.JTextField txtRellenado;
    private javax.swing.JTextField txtTotalEmp;
    // End of variables declaration//GEN-END:variables

    public  void  initComp() {
        int CantidadOperariosHabilitadosCorrida = 0;
        CantidadOperariosHabilitadosCorrida = Controlador.Service.RRHH.GestionRRHH.obtenerNumHabilitadosCorrida();
        txtTotalEmp.setText(Integer.toString(CantidadOperariosHabilitadosCorrida));
    }

    private void HabilitarMaquinas() {
                try {
            // TODO add your handling code here:
                Controlador.Service.Produccion.GestionProduccion.HabilitarTodasLasMaquinas();
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(this, "Error de conexion a la Base de Datos, intentelo mas tarde");
        }
    }

    public void ActualizarMaquinas() {
        maquinasHabilitadas = (ArrayList)Controlador.Service.Produccion.GestionProduccion.obtenerMaquinasHabilitadas();
                int numHorneadoHab = 0, numDecoradoHab =0, numRellenadoHab = 0, numEmpaquetadoHab = 0;
        int numHorneadoSel = 0, numDecoradoSel = 0, numRellenadoSel = 0, numEmpaquetadoSel = 0;
        for(int i = 0; i < maquinasHabilitadas.size(); i++){
            
            Maquina maquina = maquinasHabilitadas.get(i);
            switch (maquina.getIdTipoMaquina()) {
                case "TMA000001":
                    numHorneadoHab++;
                    break;
                case "TMA000002":
                    numRellenadoHab++;
                    break;
                case "TMA000003":
                    numDecoradoHab++;
                    break;
                case "TMA000004":
                    numEmpaquetadoHab++;
                    break;
            }           
        }
         txtHorneado.setText(Integer.toString(numHorneadoHab));
         txtDecorado.setText(Integer.toString(numDecoradoHab));
         txtRellenado.setText(Integer.toString(numRellenadoHab));
         txtEmpaquetado.setText(Integer.toString(numEmpaquetadoHab));
    }
}

